import os
import time
from urllib.parse import urlparse
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QTabWidget, QLabel, QLineEdit, QPushButton, QRadioButton, QTextEdit,
    QTreeWidget, QTreeWidgetItem, QHeaderView, QProgressBar, QHBoxLayout, QVBoxLayout, QGroupBox,
    QFileDialog, QMessageBox, QButtonGroup
)
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QTimer
from image_pro.db_utils import ImageDB
from image_pro.image_parser import extract_image_links_from_url, extract_image_links_from_file, get_filename_from_url
from image_pro.downloader import DownloadManager
import image_pro.config as config

class StatusUpdater(QThread):
    update_signal = pyqtSignal()
    
    def __init__(self):
        super().__init__()
        self.active = True
        
    def run(self):
        while self.active:
            self.update_signal.emit()
            time.sleep(2)
            
    def stop(self):
        self.active = False

class ImageDownloaderApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("图片下载工具 Pro")
        self.resize(800, 600)
        
        self.db = ImageDB(config.DB_NAME)
        self.download_manager = DownloadManager(self.db, max_workers=config.MAX_DOWNLOAD_THREADS)
        self.status_updater = StatusUpdater()
        self.status_updater.update_signal.connect(self.update_download_status)
        self.status_updater.start()
        
        self.init_ui()
        self.load_tasks()
        
    def init_ui(self):
        # 创建主TabWidget
        self.tab_widget = QTabWidget()
        self.setCentralWidget(self.tab_widget)
        
        # 创建任务选项卡
        self.create_task_tab()
        
        # 任务下载选项卡
        self.create_download_tab()
        
    def create_task_tab(self):
        """创建任务管理界面"""
        task_tab = QWidget()
        layout = QVBoxLayout(task_tab)
        
        # 来源选择部分
        source_group = QGroupBox("图片来源")
        source_layout = QVBoxLayout()
        self.source_type_group = QButtonGroup()
        
        url_rb = QRadioButton("URL")
        file_rb = QRadioButton("本地HTML文件")
        url_rb.setChecked(True)
        
        self.source_type_group.addButton(url_rb, 1)
        self.source_type_group.addButton(file_rb, 2)
        self.source_type_group.buttonClicked.connect(self.update_ui)
        
        source_layout.addWidget(url_rb)
        source_layout.addWidget(file_rb)
        source_group.setLayout(source_layout)
        
        # URL/文件输入区域
        url_group = QGroupBox()
        url_layout = QVBoxLayout(url_group)
        self.url_entry = QLineEdit()
        self.browse_button = QPushButton("浏览...")
        self.browse_button.clicked.connect(self.browse_file)
        self.browse_button.setEnabled(False)
        
        url_layout.addWidget(QLabel("URL或文件路径:"))
        h_layout = QHBoxLayout()
        h_layout.addWidget(self.url_entry)
        h_layout.addWidget(self.browse_button)
        url_layout.addLayout(h_layout)
        
        # 图片集信息区域
        info_group = QGroupBox("图片集信息")
        info_layout = QVBoxLayout(info_group)
        
        self.name_entry = QLineEdit()
        self.refer_entry = QLineEdit()
        self.path_entry = QLineEdit(os.getcwd())
        self.path_button = QPushButton("选择路径")
        self.path_button.clicked.connect(self.select_path)
        
        info_layout.addWidget(QLabel("图片集名称:"))
        info_layout.addWidget(self.name_entry)
        info_layout.addWidget(QLabel("Referer:"))
        info_layout.addWidget(self.refer_entry)
        info_layout.addWidget(QLabel("保存路径:"))
        path_layout = QHBoxLayout()
        path_layout.addWidget(self.path_entry)
        path_layout.addWidget(self.path_button)
        info_layout.addLayout(path_layout)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        self.create_button = QPushButton("创建任务")
        self.create_button.clicked.connect(self.create_task)
        self.clear_button = QPushButton("清空表单")
        self.clear_button.clicked.connect(self.clear_form)
        
        button_layout.addWidget(self.create_button)
        button_layout.addWidget(self.clear_button)
        
        # 添加所有组件到主布局
        layout.addWidget(source_group)
        layout.addWidget(url_group)
        layout.addWidget(info_group)
        layout.addLayout(button_layout)
        layout.addStretch()
        
        self.tab_widget.addTab(task_tab, "创建任务")
        
    def create_download_tab(self):
        """创建下载管理界面"""
        download_tab = QWidget()
        layout = QVBoxLayout(download_tab)
        
        # 任务列表
        list_group = QGroupBox("任务列表")
        list_layout = QVBoxLayout(list_group)
        
        self.task_tree = QTreeWidget()
        self.task_tree.setHeaderLabels(["任务名称", "状态", "进度", "路径"])
        self.task_tree.setColumnWidth(0, 250)
        self.task_tree.setColumnWidth(1, 100)
        self.task_tree.setColumnWidth(2, 100)
        self.task_tree.header().setSectionResizeMode(3, QHeaderView.Stretch)
        self.task_tree.itemClicked.connect(self.on_task_selected)
        
        list_layout.addWidget(self.task_tree)
        
        # 任务详情
        detail_group = QGroupBox("任务详情")
        detail_layout = QVBoxLayout(detail_group)
        
        self.detail_text = QTextEdit()
        self.detail_text.setReadOnly(True)
        detail_layout.addWidget(self.detail_text)
        
        # 进度条
        progress_group = QGroupBox("下载进度")
        progress_layout = QVBoxLayout(progress_group)
        
        self.progress_bar = QProgressBar()
        self.progress_label = QLabel("等待开始...")
        
        progress_layout.addWidget(self.progress_bar)
        progress_layout.addWidget(self.progress_label)
        
        # 操作按钮
        button_layout = QHBoxLayout()
        
        self.start_button = QPushButton("开始下载")
        self.start_button.clicked.connect(self.start_download)
        self.start_button.setEnabled(False)
        
        self.pause_button = QPushButton("暂停")
        self.pause_button.clicked.connect(self.pause_download)
        self.pause_button.setEnabled(False)
        
        self.delete_button = QPushButton("删除任务")
        self.delete_button.clicked.connect(self.delete_task)
        self.delete_button.setEnabled(False)
        
        self.refresh_button = QPushButton("刷新列表")
        self.refresh_button.clicked.connect(self.load_tasks)
        
        self.open_folder_button = QPushButton("打开文件夹")
        self.open_folder_button.clicked.connect(self.open_folder)
        self.open_folder_button.setEnabled(False)
        
        button_layout.addWidget(self.start_button)
        button_layout.addWidget(self.pause_button)
        button_layout.addWidget(self.delete_button)
        button_layout.addWidget(self.refresh_button)
        button_layout.addWidget(self.open_folder_button)
        
        # 添加所有组件到主布局
        layout.addWidget(list_group)
        layout.addWidget(detail_group)
        layout.addWidget(progress_group)
        layout.addLayout(button_layout)
        
        self.tab_widget.addTab(download_tab, "任务下载")
        
        # 当前选中的任务
        self.current_task_uid = None
    
    def update_ui(self):
        """根据选择的来源类型更新UI"""
        is_url = self.source_type_group.checkedId() == 1
        self.browse_button.setEnabled(not is_url)
        self.url_entry.clear()
        if is_url:
            self.url_entry.setPlaceholderText("请输入网页URL")
        else:
            self.url_entry.setPlaceholderText("请选择HTML文件")
    
    def browse_file(self):
        """浏览本地HTML文件"""
        file_path, _ = QFileDialog.getOpenFileName(self, "选择HTML文件", "", "HTML文件 (*.html *.htm)")
        if file_path:
            self.url_entry.setText(file_path)
    
    def select_path(self):
        """选择保存路径"""
        folder_path = QFileDialog.getExistingDirectory(self, "选择保存路径", "")
        if folder_path:
            self.path_entry.setText(folder_path)
    
    def clear_form(self):
        """清空表单"""
        self.url_entry.clear()
        self.name_entry.clear()
        self.refer_entry.clear()
        self.path_entry.setText(os.getcwd())
    
    def create_task(self):
        """创建下载任务"""
        # 获取表单数据
        name = self.name_entry.text().strip()
        refer = self.refer_entry.text().strip()
        path = self.path_entry.text().strip()
        source = self.url_entry.text().strip()
        is_url = self.source_type_group.checkedId() == 1
        
        # 验证输入
        if not name:
            QMessageBox.warning(self, "输入错误", "请输入图片集名称")
            return
        
        if not source:
            QMessageBox.warning(self, "输入错误", "请输入URL或选择HTML文件")
            return
        
        if not path:
            QMessageBox.warning(self, "输入错误", "请选择保存路径")
            return
        
        # 解析图片链接
        try:
            if is_url:
                image_urls = extract_image_links_from_url(source, refer)
                source_type = 'url'
            else:
                image_urls = extract_image_links_from_file(source)
                source_type = 'file'
            
            if not image_urls:
                QMessageBox.warning(self, "解析错误", "未找到任何图片链接")
                return
            
            # 创建保存目录
            save_path = os.path.join(path, name)
            os.makedirs(save_path, exist_ok=True)
            
            # 创建任务
            task_uid, task_id = self.db.create_image_task(
                name=name,
                refer=refer,
                path=save_path,
                url=source,
                source_type=source_type,
                total_images=len(image_urls)
            )
            
            # 创建下载项
            for img_url in image_urls:
                filename = get_filename_from_url(img_url)
                file_path = os.path.join(save_path, filename)
                
                self.db.create_image_download(
                    task_uid=task_uid,
                    url=img_url,
                    path=file_path,
                    filename=filename
                )
            
            QMessageBox.information(self, "成功", f"成功创建任务，共{len(image_urls)}张图片")
            self.clear_form()
            self.load_tasks()
            self.tab_widget.setCurrentIndex(1)  # 切换到下载选项卡
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"创建任务失败: {str(e)}")
    
    def load_tasks(self):
        """加载任务列表"""
        self.task_tree.clear()
        
        tasks = self.db.get_all_tasks()
        for task in tasks:
            task_id, uid, name, state, total, downloaded, path = task
            
            item = QTreeWidgetItem(self.task_tree)
            item.setText(0, name)
            item.setText(1, state)
            item.setText(2, f"{downloaded}/{total}")
            item.setText(3, path)
            item.setData(0, Qt.UserRole, uid)
    
    def on_task_selected(self, item):
        """选中任务时的操作"""
        self.current_task_uid = item.data(0, Qt.UserRole)
        task = self.db.get_task_by_uid(self.current_task_uid)
        
        if task:
            # 更新详情
            task_id, name, refer, path, url, source_type, uid, state, total, downloaded, create_time, update_time = task
            
            details = f"任务名称: {name}\n"
            details += f"创建时间: {create_time}\n"
            details += f"来源类型: {'URL' if source_type == 'url' else '本地文件'}\n"
            details += f"来源: {url}\n"
            details += f"Referer: {refer}\n"
            details += f"保存路径: {path}\n"
            details += f"状态: {state}\n"
            details += f"进度: {downloaded}/{total} ({downloaded/total*100:.1f}% 完成)"
            
            self.detail_text.setText(details)
            
            # 更新进度条
            self.progress_bar.setMaximum(total)
            self.progress_bar.setValue(downloaded)
            self.progress_label.setText(f"{downloaded}/{total} ({downloaded/total*100:.1f}%)")
            
            # 更新按钮状态
            self.start_button.setEnabled(state in [config.STATUS_PENDING, config.STATUS_READY, config.STATUS_PAUSED])
            self.pause_button.setEnabled(state == config.STATUS_DOWNLOADING)
            self.delete_button.setEnabled(True)
            self.open_folder_button.setEnabled(True)
    
    def start_download(self):
        """开始下载任务"""
        if not self.current_task_uid:
            return
        
        self.download_manager.start_task(self.current_task_uid)
        self.start_button.setEnabled(False)
        self.pause_button.setEnabled(True)
    
    def pause_download(self):
        """暂停下载任务"""
        if not self.current_task_uid:
            return
        
        self.download_manager.pause_task(self.current_task_uid)
        self.start_button.setEnabled(True)
        self.pause_button.setEnabled(False)
    
    def delete_task(self):
        """删除任务"""
        if not self.current_task_uid:
            return
        
        reply = QMessageBox.question(self, "确认删除", 
                                     "确定要删除此任务吗？这将从数据库中删除任务记录，但不会删除已下载的文件。",
                                     QMessageBox.Yes | QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            self.download_manager.pause_task(self.current_task_uid)
            self.db.delete_task(self.current_task_uid)
            self.load_tasks()
            self.detail_text.clear()
            self.progress_bar.setValue(0)
            self.progress_label.setText("等待开始...")
            self.current_task_uid = None
            self.start_button.setEnabled(False)
            self.pause_button.setEnabled(False)
            self.delete_button.setEnabled(False)
            self.open_folder_button.setEnabled(False)
    
    def open_folder(self):
        """打开保存文件夹"""
        if not self.current_task_uid:
            return
        
        task = self.db.get_task_by_uid(self.current_task_uid)
        if task and os.path.exists(task[3]):  # path字段索引
            import subprocess
            if os.name == 'nt':  # Windows
                os.startfile(task[3])
            elif os.name == 'posix':  # macOS/Linux
                subprocess.call(['open' if os.uname().sysname == 'Darwin' else 'xdg-open', task[3]])
    
    def update_download_status(self):
        """更新下载状态"""
        if not self.current_task_uid:
            return
        
        task = self.db.get_task_by_uid(self.current_task_uid)
        if task:
            # 更新进度
            downloaded = task[10]  # downloaded字段索引
            total = task[9]  # total_images字段索引
            state = task[7]  # state字段索引
            
            # 确保downloaded是整数类型
            try:
                downloaded_int = int(downloaded)
            except (ValueError, TypeError):
                downloaded_int = 0
            
            # 更新UI
            self.progress_bar.setValue(downloaded_int)
            if total > 0:
                try:
                    total_int = int(total)
                    percentage = downloaded_int / total_int * 100
                    self.progress_label.setText(f"{downloaded_int}/{total_int} ({percentage:.1f}%)")
                except (ValueError, TypeError, ZeroDivisionError):
                    self.progress_label.setText(f"{downloaded_int}/{total} (0.0%)")
            
            # 更新按钮状态
            self.start_button.setEnabled(state in [config.STATUS_PENDING, config.STATUS_READY, config.STATUS_PAUSED])
            self.pause_button.setEnabled(state == config.STATUS_DOWNLOADING)
            
            # 更新任务列表中的状态
            for i in range(self.task_tree.topLevelItemCount()):
                item = self.task_tree.topLevelItem(i)
                if item.data(0, Qt.UserRole) == self.current_task_uid:
                    item.setText(1, state)
                    item.setText(2, f"{downloaded}/{total}")
                    break
    
    def closeEvent(self, event):
        """关闭窗口时的操作"""
        self.status_updater.stop()
        self.download_manager.stop_all()
        self.db.close_connection()
        event.accept()

def run():
    import sys
    app = QApplication(sys.argv)
    window = ImageDownloaderApp()
    window.show()
    sys.exit(app.exec_())

def main():
    run()